<?php

/**
 * Created by PhpStorm.
 * User: UEWARE
 * Date: 2019-9-3
 * Time: 14:48:06
 */
namespace App\Http\Controllers\WeChat\Diary\V1\Travels;

use App\Http\Controllers\WeChat\WeChatController;
use App\Models\TravelsContentModel;
use App\Models\TravelsModel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class AddController extends WeChatController
{
    /**
     * 添加游记
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function index(Request $request)
    {
        // 获取当前data值
        $data = $request->input();

        $diary = json_decode($data['diary'], true);

        // 数据处理
        $meta = $diary['meta'];
        $meta['user_id'] = $this->userId;
        $content = $diary['list'];
        // 添加回滚
        DB::beginTransaction();
        try {
            $travels = TravelsModel::query()->create($meta);
            foreach($content as &$val){
                $val['t_id'] = $travels->id;
                $val['address'] = json_encode($val['poi']);
                unset($val['poi']);
                unset($val['description']);
                $val['created_at'] = time();
                $val['updated_at'] = time();

            }

            TravelsContentModel::query()->insert($content);
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return error(700001);
        }

        return success();
    }
}